import React, { useState, useEffect, useRef, Suspense } from 'react';
import { Layout, Space, Spin, Button } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';

import { useHistory } from 'react-router-dom';
import { RouteConfigComponentProps, renderRoutes } from 'react-router-config';

import { logoutSys } from '../utils';
import { checkPermission, getMenuPermissionMgr, PermissionMgr } from '../permission/Index';
import { getStore } from 'store/store';
import UserArea from 'components/UserArea';
import DownloadModel from 'admin/components/DownloadModel';

import { PermissionType } from 'admin/schema/PermissionTypes';
import { UserNotice } from 'admin/components/UserNotice';
import CheckInOut from 'seats/components/CheckInOut';
import DeviceCheck from 'seats/components/DeviceCheck';

// import { checkValidate } from 'utils/tools';
import SipComponent from 'components/SipComponent/SipComponent';
import { SideMenu } from './SideMenu';
import { siderBarConfig, systemOneLeverMenu } from 'permission/menuConfig';
import './BasicLayout.scss';
import { BreadCrumb } from './BreadCrumb';
import WebLogo from './WebLogo';
import BillingSystemLink from 'components/BillingSystemLink';
import { vpnCheckInit } from 'utils/vpnCheck';

const { Header, Content, Sider } = Layout;

const BasicLayout: React.FC<RouteConfigComponentProps> = props => {
  const history = useHistory();
  const isUnMont = useRef<boolean>(false); // 防止内存溢出

  const [collapsed, setCollapsed] = useState<boolean>(false);
  const [canRender, setCanRender] = useState<boolean>(false);
  const [showDownload, setShowDownload] = useState<boolean>(false);
  const [isshow, setIsshow] = useState(true);

  const STORE = getStore();

  /**控制侧边栏显示/隐藏*/
  const toggleSider = () => setCollapsed(prev => !prev);

  /**读取权限数据后再渲染页面*/
  const initMenuPermission = async () => {
    try {
      await (getMenuPermissionMgr() as PermissionMgr).waitFetchPermission();
      if (!isUnMont.current) {
        setCanRender(true);
        vpnCheckInit();
      }
    } catch (error) {
      console.error('fetch permissionList failed, stop render!******logout!!!');
      // debugger;
      if (process.env.REACT_APP_LOGIN_NO_CHECK != '1') {
        logoutSys(true);
      }
    }
  };

  /**
   * 检查页面是否有权限
   * 思路：检查该页面路由是否在左侧菜单中并判断是否有权限
   * 如果存在于左侧菜单（hidden=true也算）同时没有权限，则判定该页面没有权限
   */
  const checkPagePermission = (path: string): boolean => {
    // 以下代码，方便调试用-若后端没有添加页码权限，可以通过直接输入path打开页面,调试开发完，要注释掉
    // if (true) {
    //   return true;
    // }
    // console.log(path, "检查页面权限");
    // debugger
    if (path === '/' || path === '/webapp' || path === '/webseats') {
      return true;
    }
    // 是否在左侧菜单中
    let hasPath = false;
    siderBarConfig.forEach(item => {
      if (item.path === path) {
        hasPath = true;
      }
      item.children &&
        item.children.forEach(son => {
          if (son.path === path) {
            hasPath = true;
          }
        });
    });
    const hasPermission = checkPermission(path as PermissionType);
    return !(hasPath && !hasPermission);
  };
  /**
   * 获得一个一级菜单下有权限的第一个二级菜单
   * ex:
   * input:   "/account"
   * return:  "/account/user"
   */
  const getPermissionPath = (parentPath: string): string => {
    const menuCollection = siderBarConfig;
    let targetPath = '';
    menuCollection.forEach(item => {
      if (item.path === parentPath) {
        const childrenMenus = item.children || [];
        const length = childrenMenus.length;
        if (length) {
          // 存在二级目录，有子菜单
          for (let i = 0; i < length; i++) {
            const child = childrenMenus[i];
            if (checkPermission(child.path as PermissionType)) {
              targetPath = child.path;
              break;
            }
          }
        } else {
          // 只有一级目录，没有子菜单
          targetPath = parentPath;
        }
      }
    });
    return targetPath || '/';
  };
  /**
   * 控制头部icon抽屉，显示/隐藏
   */
  const toggleShow = (str: string) => {
    if (str === 'download') {
      // 打开-下载抽屉
      setShowDownload(true);
    } else {
      // 关闭-所有抽屉
      setShowDownload(false);
    }
  };
  /**渲染页面-全屏（机器人流程预览页面）*/
  useEffect(() => {
    STORE.addChangeEvent('isFullScreen', val => {
      toggleSider();
      setIsshow(prev => !prev);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /**
   * 自动重定向
   */
  useEffect((): any => {
    initMenuPermission();
    if (!canRender) {
      // 页面不可见
      return;
    }
    // 测试过期天数函数，上线隐藏
    // checkValidate();
    let pathName = location.pathname;
    // 路径不是根路径，是以'.../'结尾，例如："/webapp/account/"，需要去掉末尾'/'
    if (pathName !== '/' && pathName.slice(-1) === '/') {
      pathName = pathName.slice(0, -1);
    }

    // 页面可见，代表菜单权限已经获取到，可进行权限查询
    const hasPagePermission = checkPagePermission(pathName);
    console.log('BasicLayout组件-页面路径', pathName, hasPagePermission);
    if (hasPagePermission) {
      // 当前页面路径，没有权限
      // 用户没有任何菜单权限跳转到空白页
      if (getMenuPermissionMgr().getValue().length === 0) {
        history.push('/blank');
      }
      // 用户输入根目录跳转到系统有权限的第一个页面
      if (['/webapp', '/webseats', '/'].includes(pathName)) {
        history.push(STORE.get('firstMenu').path);
      }
      // 管理端：用户输入一个一级目录，跳转到该目录下有权限的第一个页面
      if (systemOneLeverMenu.includes(pathName)) {
        history.push(getPermissionPath(pathName));
      }
    } else {
      // 没有页面权限
      history.push('/401');
    }

    return () => (isUnMont.current = true); // 卸载时回调
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [canRender, location.pathname]);

  return (
    <>
      {canRender ? (
        <Layout className="page-layout">
          <Sider
            width={185}
            collapsible
            collapsedWidth="0"
            collapsed={collapsed}
            trigger={null}
            breakpoint="lg"
          >
            <WebLogo />
            <SideMenu />
          </Sider>
          <SipComponent />
          <Layout className={isshow ? 'right-layout not-full-page' : 'right-layout full-page'}>
            <Header className="right-layout-header">
              <Button
                type="primary"
                onClick={toggleSider}
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              />
              <UserArea />
              <DownloadModel fn={toggleShow} visible={showDownload} />
              <DeviceCheck />
              {checkPermission('/seats/callTask') && <CheckInOut />}
              <UserNotice />
              {checkPermission('/billingSystem') && <BillingSystemLink />}
            </Header>
            <BreadCrumb />
            <Content className="right-layout-content">
              <Suspense
                fallback={
                  <Space direction="vertical" className="all-scre" align="center" size="middle">
                    <Spin size="default" />
                    <div>正在加载页面……</div>
                  </Space>
                }
              >
                {renderRoutes(props.route?.routes)}
              </Suspense>
            </Content>
          </Layout>
        </Layout>
      ) : (
        <Space direction="vertical" className="all-scre" align="center" size="middle">
          <Spin size="default" />
          <div>正在加载权限数据</div>
        </Space>
      )}
    </>
  );
};
export default BasicLayout;
